<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\api\model\IntegralGoods;
use app\api\model\CouponDsecModel as StoreCoupon;
use app\api\model\Users;
use think\Request;

class PonintsRedemptionGoods
{
    /**
     *积分商品列表查询
     * @return \think\Response
     */
    public function index()
    {
        // 查询积分商品信息
        $GoodsData = IntegralGoods::with('goods')->select();

        return json(['code'=>200,'msg'=>'查询成功','data'=>$GoodsData]);
    }

    public function exchangeGoods(Request $request)
    {
        // 接前台传来的商品id
        $goods_id = $request->id;

        // 自定义用户id为1
        $uid = 1;
        // 查询用户表用户拥有的积分
        $PointsUser = Users::where('id',$uid)->find();

        // 查询兑换每个商品所需要的积分
        $GoodsPoints = IntegralGoods::where('id',$PointsUser)->find();

        // 当用户兑换商品时进行积分的加减
        if ($PointsUser['points'] < $GoodsPoints['integral']){
            return json(['code'=>4001,'msg'=>'您的积分不足，无法进行兑换','data'=>'']);
        }

        if ($PointsUser['points'] > $GoodsPoints['integral']){

            $PointsUser->save( $PointsUser['points'] - $GoodsPoints['integral']);

            // 根据当前选择的商品id查询出兑换的商品
            $coupon = StoreCoupon::where('id',$PointsUser)->find();


            // 把优惠券放到用户包内(包含商品的信息，已经对应的用户id)
            $userCoupon = SelfGoods:: create([
                'u_id' => $PointsUser['id'],
                'title' => $GoodsPoints['title'],
            ]);
        }

        return json(['code'=>200,'msg'=>'商品兑换成功']);
    }
}
